package com.xywy.wjk;

import java.util.ArrayList;
import java.util.List;

import m.framework.utils.Utils;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xywy.R;
import com.xywy.common.BaseActivity;
import com.xywy.common.app.MainApplication;
import com.xywy.common.bean.ConnectedDevice;
import com.xywy.common.util.FileUtil;
import com.xywy.common.util.ble.util.BLEBloodPresureProvider;
import com.xywy.common.util.ble.util.BLEWeightScaleProvider;
import com.xywy.wjk.observer.ObserverConstants;
import com.xywy.wjk.util.DeviceState;
import com.xywy.wjk.util.WjkConstant;
import com.xywy.wjk.widget.TipDialog;
import com.xywy.wjk.widget.TipDialog.OkayListener;

/**
 * 扫描蓝牙设备
 * 
 * @author yangyu
 * 
 */
public class ScanBLEActivity extends BaseActivity implements OnClickListener {

	private static final int REQUEST_ENABLE_BT = 0;
	private static final long SCAN_PERIOD = 15000;
	public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
	public static final String USER_WEIGHT_DATA_1 = "data1";
	public static final String USER_WEIGHT_DATA_2 = "data2";

	AnimationSet animationSet1;
	AnimationSet animationSet2;

	private ImageView anim_iv_1;
	private ImageView anim_iv_2;

	private ImageView iv_me; // 我自己的头像
	private ImageView iv_weight; // 体重秤；
	private ImageView iv_xueya; // 血压计？
	private ImageView iv_tiwen;

	private BluetoothAdapter mBluetoothAdapter; // 获取蓝牙设备；
//	private BLEWeightScaleProvider WCutils;
//	private BLEBloodPresureProvider BPutils;

	private List<BluetoothDevice> devices; // 蓝牙设备容器；
	private BluetoothDevice curWeightDevice, cuXueyaDevice;
	private Button bt_title_back; // 返回按钮
	private TextView tv_title_back; // 返回蚊子

	boolean mScanning;

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.start_scan_ble);
		this.initView();
		this.preInit();
		this.loadData();
		MainApplication.addSpeciall(this);
		registerReceiver(new BlueReceiver(), new IntentFilter(BLUE_ACTION));
	}

	public static final String BLUE_ACTION = "android.bluetooth.BluetoothAdapter.ACTION_STATE_CHANGED";
	public class BlueReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context arg0, Intent intent) {
			if(BLUE_ACTION.equals(intent.getAction())){
				System.out.println("蓝牙变化了------");
				flag = true;
			}
		}
		
	}
	@Override
	protected void onResume() {
		super.onResume();
		handler.postDelayed(new Runnable() {

			@Override
			public void run() {
				scanLeDevice(true);
			}
		}, 1000);
	}

	@Override
	protected void onPause() {
		super.onPause();
		scanLeDevice(false);
	}

	/**
	 * 处理一些基本引用。
	 */
	@Override
	public void preInit() {
		MainApplication app = MainApplication.getInstance();
		mBluetoothAdapter = app.getWeightBleAdapter();
//		WCutils = app.getWeightBleProvider();
//		BPutils = app.getBloodPBleProvider();
//		if (WCutils != null) {
//			WCutils.disconnect(); // 先断开设备连接
//			// WCutils.close(); // 选择设备的时候就把当前连接是设备断开连接；
//		}
//		if (BPutils != null) {
//			BPutils.disconnect(); // 先断开设备连接
//			// BPutils.close(); // 选择设备的时候就把当前连接是设备断开连接；
//		}
		devices = new ArrayList<BluetoothDevice>();
		/* 连接蓝牙的条件 */

	}

	/**
	 * 如果没有打开蓝牙设备，提醒用户去打开蓝牙设备；
	 */
	public void OpenBluetooth() {
		if (!mBluetoothAdapter.isEnabled()) {
			if (!mBluetoothAdapter.isEnabled()) {
				Intent enableBtIntent = new Intent(
						BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
			}
		}
	}

	@Override
	public void loadData() {

	}

	@Override
	public void initView() {

		anim_iv_1 = (ImageView) findViewById(R.id.anim_iv_1);
		anim_iv_2 = (ImageView) findViewById(R.id.anim_iv_2);

		iv_xueya = (ImageView) findViewById(R.id.iv_xueya);
		iv_me = (ImageView) findViewById(R.id.iv_me);
		iv_weight = (ImageView) findViewById(R.id.iv_weight);
		iv_tiwen = (ImageView) findViewById(R.id.iv_tiwen);

		tv_title_back = (TextView) findViewById(R.id.tv_title_back);
		bt_title_back = (Button) findViewById(R.id.bt_title_back);

		iv_xueya.setOnClickListener(this);
		iv_me.setOnClickListener(this);
		iv_tiwen.setOnClickListener(this);
		iv_weight.setOnClickListener(this);
		bt_title_back.setOnClickListener(this);
		tv_title_back.setOnClickListener(this);

		animationSet1 = new AnimationSet(true);
		animationSet2 = new AnimationSet(true);

		startanima1(anim_iv_1, 0);
		startanima2(anim_iv_2, 500);

	}

	// 代码冗余。 动画代码不能复用？？ 此部分代码可以在AnimImageView中处理；
	/**
	 * 开始动画
	 * 
	 * @param time
	 *            延迟启动时间；
	 */
	private void startanima1(final ImageView iv, long time) {

		handler.postDelayed(new Runnable() {

			@Override
			public void run() {
				ScaleAnimation sa = new ScaleAnimation(0.0f, 1.7f, 0.0f, 1.7f,
						Animation.RELATIVE_TO_SELF, 0.5f,
						Animation.RELATIVE_TO_SELF, 0.5f);

				AlphaAnimation aa = new AlphaAnimation(1.0f, 0.0f);
				aa.setRepeatCount(999);
				sa.setRepeatCount(999);
				animationSet1.addAnimation(sa);
				animationSet1.addAnimation(aa);
				animationSet1.setDuration(2000);
				animationSet1.setRepeatCount(999);
				animationSet1.setFillAfter(true);// 动画执行完后是否停留在执行完的状态
				iv.startAnimation(animationSet1);

			}
		}, time);
	}

	/**
	 * 开始动画
	 * 
	 * @param time
	 *            延迟启动时间；
	 */
	private void startanima2(final ImageView iv, long time) {
		handler.postDelayed(new Runnable() {

			@Override
			public void run() {
				ScaleAnimation sa = new ScaleAnimation(0.0f, 1.7f, 0.0f, 1.7f,
						Animation.RELATIVE_TO_SELF, 0.5f,
						Animation.RELATIVE_TO_SELF, 0.5f);

				AlphaAnimation aa = new AlphaAnimation(1.0f, 0.0f);
				aa.setRepeatCount(999);
				sa.setRepeatCount(999);
				animationSet2.addAnimation(sa);
				animationSet2.addAnimation(aa);
				animationSet2.setDuration(2000);
				animationSet2.setRepeatCount(999);
				animationSet2.setFillAfter(true);// 动画执行完后是否停留在执行完的状态
				iv.startAnimation(animationSet2);

			}
		}, time);
	}

	/**
	 * 开始扫描
	 * 
	 * @param enable
	 *            true 开始扫描 false 停止扫描
	 */
	TipDialog dialog;
	public boolean flag = true;
	public void scanLeDevice(final boolean enable) {

		if (!mBluetoothAdapter.isEnabled()) {

		     dialog = new TipDialog(this, TipDialog.VIEW_TIP);
			dialog.setTitleAndContent("蓝牙未开启", "检测到你没有打开手机蓝牙，请打开后再试");
			dialog.setOkayCallback(new OkayListener() {

				@Override
				public void okay() {
					dialog.dismiss();
					ScanBLEActivity.this.finish();
				}
			});
			dialog.getDialog().setCancelable(false);
			if(flag){
				flag = false;
				dialog.show();
			}
			// OpenBluetooth();

		} else {
			if (enable) {
				handler.postDelayed(getBLEDevices, SCAN_PERIOD);
				mScanning = true;
				mBluetoothAdapter.startLeScan(mLeScanCallback);
			} else {
				mScanning = false;
				mBluetoothAdapter.stopLeScan(mLeScanCallback);
			}
		}

	}

	/**
	 * 扫描未被连接的设备；
	 */
	Runnable getBLEDevices = new Runnable() {
		public void run() {
			mScanning = false;
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
			if (devices.size() == 0) {
				Log.d(TAG, "没有扫描到设备");
				Toast.makeText(ScanBLEActivity.this,
						"没有扫描到蓝牙设备，为了节省电量已经为您停止扫描", Toast.LENGTH_SHORT).show();
			} else {
				Log.d(TAG, "已经发现设备");
			}
		}
	};

	/**
	 * 发现蓝牙设备的回调；
	 */
	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

		@Override
		public void onLeScan(final BluetoothDevice device, int rssi,
				byte[] scanRecord) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (null == device.getName()) {
						return;
					}
					if (!devices.contains(device)) {
						devices.add(device);
					}
					/* 没有体重秤的时候显示体重秤 */
					if (iv_weight.getVisibility() != View.VISIBLE
							&& isHaveWeight()) {
						iv_weight.setVisibility(View.VISIBLE);
						curWeightDevice = device;
					}
					/* 其他控件同上 */
					if (iv_xueya.getVisibility() != View.VISIBLE
							&& isHaveBlood()) {
						iv_xueya.setVisibility(View.VISIBLE);
						cuXueyaDevice = device;
					}
					
					/* 体温 */
					if (iv_tiwen.getVisibility() != View.VISIBLE
							&& isHaveTemp()) {
						iv_tiwen.setVisibility(View.VISIBLE);
//						cuXueyaDevice = device;
					}
				}

			});
		}
	};

	/**
	 * 是否有体重秤；
	 * 
	 * @return true 有， false 没有
	 */
	private boolean isHaveWeight() {
		for (BluetoothDevice device : devices) {
			if (device.getName().equals("Xunyiwenyao")) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 是否有血压计
	 * 
	 * @return
	 */
	private boolean isHaveBlood() {
		for (BluetoothDevice device : devices) {
			if (device.getName().startsWith("KBB")) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 是否有体温计
	 * 
	 * @return
	 */
	private boolean isHaveTemp() {
		String Thermometer = "DoouYa Thermometer";
		for (BluetoothDevice device : devices) {
			if (device.getName().contains(Thermometer)) {
				return true;
			}
		}
		return false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// User chose not to enable Bluetooth.
		if (requestCode == REQUEST_ENABLE_BT
				&& resultCode == Activity.RESULT_CANCELED) {
			finish();
			return;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public static final int WEIGHT_RESULT_CDOE = 1001;
	public static final int BLOOD_RESULT_CDOE = 1002;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_weight:
			// DeviceState.saveDeviceMac(this, DeviceState.DEVICE_WEIGHT_SCALE,
			// curWeightDevice.getAddress());
//			getContentResolver().notifyChange(ObserverConstants.CHANGE_WEIGHT,
//					null);
//			MainApplication.finishSpeciall();
//			ConnectedDevice blood_device = FileUtil.getBloodDevice();
//			if(blood_device.isConnected()){//断开血压连接体重
//				Intent intent = new Intent(WjkConstant.CONNECT_WEIGHT_ACTION_DISCONNECT);
//				sendBroadcast(intent);
//			}else { //直接连接体重
//				Intent intent = new Intent(WjkConstant.CONNECT_WEIGHT_ACTION);
//				sendBroadcast(intent);
//			}
			connectTo(WEIGHT_SCALE);
//			MainApplication.finishSpeciall();
			break;
		case R.id.iv_xueya:
			connectTo(BLOOD_PRESURE);
//			getContentResolver().notifyChange(ObserverConstants.CHANGE_BLOOD,
//					null);
//			MainApplication.finishSpeciall();
			
			// DeviceState.saveDeviceMac(this, DeviceState.DEVICE_BLOOD_PAUSERE,
			// cuXueyaDevice.getAddress());
//			ConnectedDevice weight_device = FileUtil.getWeightDevice();
//			if(weight_device.isConnected()){ //断开体重连接血压
//				Intent intent = new Intent(WjkConstant.CONNECT_BLOOD_ACTION_DISCONNET);
//				sendBroadcast(intent);
//			}else {//直接连接血压
//				Intent intent = new Intent(WjkConstant.CONNECT_BLOOD_ACTION);
//				sendBroadcast(intent);
//			}
//			MainApplication.finishSpeciall();
			break;
		case R.id.iv_tiwen:
			connectTo(TEMP_);
			break;
		case R.id.iv_me:
			break;

		case R.id.tv_title_back:
		case R.id.bt_title_back:
			this.finish();
			break;

		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mBluetoothAdapter != null) {
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
		}

	}

	private int WEIGHT_SCALE = 0;
	private int TEMP_ = 1;
	private int BLOOD_PRESURE = 2;
	public void connectTo(int cur_device) {
		ConnectedDevice current_device = FileUtil.getCurrentDevice();
		//蓝牙未开启
		if(current_device.isConnected()){
			if(cur_device ==WEIGHT_SCALE ){
				Intent intent = new Intent(WjkConstant.CONNECT_WEIGHT_ACTION_DISCONNECT);
				sendBroadcast(intent);
				MainApplication.finishSpeciall();
			}else if(cur_device == BLOOD_PRESURE){
				Intent intent = new Intent(WjkConstant.CONNECT_BLOOD_ACTION_DISCONNET);
				sendBroadcast(intent);
				MainApplication.finishSpeciall();
			}else if(cur_device == TEMP_){
				Intent intent = new Intent(WjkConstant.CONNECT_TEMPUT_ACTION_DISCONNECT);
				sendBroadcast(intent);
				MainApplication.finishSpeciall();
//				Toast.makeText(SelectBrandActivity.this,
//						"暂无体温设备", Toast.LENGTH_LONG).show();
			}
		}else {
			if(cur_device ==WEIGHT_SCALE ){
				Intent intent = new Intent(WjkConstant.CONNECT_WEIGHT_ACTION);
				sendBroadcast(intent);
				MainApplication.finishSpeciall();
			}else if(cur_device == BLOOD_PRESURE){
				Intent intent = new Intent(WjkConstant.CONNECT_BLOOD_ACTION);
				sendBroadcast(intent);
				MainApplication.finishSpeciall();
			}else if(cur_device == TEMP_){
//				Toast.makeText(SelectBrandActivity.this,
//						"暂无体温设备", Toast.LENGTH_LONG).show();
				Intent intent = new Intent(WjkConstant.CONNECT_TEMPUT_ACTION);
				sendBroadcast(intent);
				MainApplication.finishSpeciall();
			}
		}
		
	}
	
}
